const db = require("./db.js")
const inquirer = require("inquirer")

module.exports.add = async (title) => {
  //读取之前的任务
  const list = await db.read()
  //添加一个title任务
  list.push({title, done: false})
  //存储任务到文件
  await db.write(list)
}

module.exports.clear = async () => {
  await db.write([])
}


function markAsDone(list, index) {
  list[index].done = true
  db.write(list)
}

function markAsFailure(list, index) {
  list[index].done = false
  db.write(list)
}

function updateTitle(index, list) {
  inquirer.prompt(
    {
      type: "input",
      name: "title",
      message: "What's your new task name?",
      default: list[index].title
    }
    ,).then((answers) => {
    list[index].title = answers.title
    db.write(list)
  })
}

function remove(list, index) {
  list.splice(index, 1)
  db.write(list)
}

function askForAction(list, index) {
  const actions = {markAsDone, markAsFailure, remove, updateTitle}
  inquirer.prompt({
    type: "list", name: "action",
    message: "请选择操作",
    choices: [
      {name: "退出", value: "quit"},
      {name: "完成", value: "markAsDone"},
      {name: "失败", value: "markAsFailure"},
      {name: "改名", value: "updateTitle"},
      {name: "删除", value: "remove"}
    ]
  }).then(answers2 => {
    const action = actions[answers2.action]
    action && action(list, index)
  })
}

function askForCreateTask(list) {
  inquirer.prompt(
    {
      type: "input",
      name: "title",
      message: "Please input the new task name",
    }
    ,).then((answers) => {
    list.push({
      title: answers.title,
      done: false
    })
    db.write(list)
  })
}

function printTasks(list) {
  inquirer
    .prompt(
      {
        type: "list",
        name: "index",
        message: "选择任务进行操作?",
        choices: [{name: "exit", value: "-1"}, ...list.map((task, index) => {
          return {name: `${task.done ? "[x]" : "[_]"} ${index + 1}-${task.title}`, value: index.toString()}
        }), {name: "+创建任务", value: "-2"}]
      })
    .then((answers) => {
      const index = parseInt(answers.index)
      if (index >= 0) {
        //选中了一个任务
        askForAction(list, index)
      } else if (index === -2) {
        //创建任务
        askForCreateTask(list)
      }
    })
}

module.exports.showAll = async () => {
  //读取之前的任务
  const list = await db.read()
  //打印之前的任务
  //printTasks
  printTasks(list)
}